import { useState } from 'react';

const resolveValue = (e: any) => {
  return e?.target?.value ?? e?.target?.checked ?? e?.value ?? e
}

type Options = {
  filed?: string
}

export function useModel<T = any>(value: T, options?: Options) {
  const { filed = "value" } = options ?? {}
  const [state, setState] = useState(value)
  const bindState = {
    [filed]: state,
    onInput: (e: any) => setState(resolveValue(e)),
    onChange: (e: any) => setState(resolveValue(e))
  }

  return [state, bindState, setState] as const
}